/**
 * @class UI-功能类-目标指引圈
 * @author DuskyHuang 圣子
 */

import { _decorator, Component, Node, Camera, Animation, Vec3, Label } from 'cc';
import { core } from 'cfw';
import { KM_OF_LY, TransformEnum } from 'const';
import { View, UI } from 'notifications';
import { cosmos, gizmos, visit } from 'proxies';
const { ccclass, property } = _decorator;

@ccclass('target-indicator')
export class TargetIndicator extends Component {

    @property(Camera) public mainCamera: Camera = null;
    @property(Node) public circles: Node = null;
    @property(Label) public distance: Label = null;

    protected onLoad(): void {
        this._init();
    }

    protected start(): void {
        this.circles.active = false;
    }

    private _init(): void {
        this._anim = this.circles.getComponent(Animation);
        this._anim.on(Animation.EventType.FINISHED, this._playOver, this);
        core.on(View.Transform.ZOOM_OVER, this._playAnim, this);
        core.on(View.Transform.FACE_OVER, () => this._forgive = true);
        core.on(UI.IGNORE_TARGET_ONCE, () => this._ignore = true);
    }
    protected onDestroy(): void { core.unload(this); }

    private _playAnim(): void {
        const { transEnum } = visit.transInfo;
        if (this._ignore) {
            this._ignore = false;
            return;
        }
        if (SHOW_CIRCLE_ENUMS.contains(transEnum)) {
            this._playing = true;
            this.circles.active = true;
            this._anim.play();
        }
    }

    private _playOver(): void {
        this._playing = false;
        this.circles.active = false;
    }

    protected lateUpdate(dt?: time.sec): any {
        this.distance.node.active = false;
        if (this._playing) {
            const { target } = visit.transInfo, { showTarget } = gizmos;
            if (!target || !showTarget) return this.circles.active = false;
            if (this._forgive) {
                this.circles.active = true;
            } else {
                const { worldPosition: sp } = target.node, { forward, worldPosition: mp } = this.mainCamera.node;
                if (Vec3.dot(forward, Vec3.subtract(v3a, sp, mp)) < 0) return this.circles.active = false;
                const dist = 10 ** cosmos.pow10 * v3a.length() * KM_OF_LY;
                this.distance.string = dist.toFixed(0) + ' km';
                this.distance.node.active = true;
                this.circles.active = true;
                this.mainCamera.convertToUINode(sp, this.node.parent, v3a);
                this.circles.setPosition(v3a);
            }
        }
        this._forgive = false;
    }

    private _forgive: boolean = false;
    private _ignore: boolean = false;
    private _anim: Animation;
    private _playing: boolean = false;
}

const v3a = new Vec3;
const SHOW_CIRCLE_ENUMS = [
    TransformEnum.SUN_2_PLN, TransformEnum.SUN_2_SAT, TransformEnum.PLN_2_PLN,
    TransformEnum.PLN_2_SUN, TransformEnum.SAT_2_SUN, TransformEnum.SUN_2_SPC,
    TransformEnum.SPC_2_SUN,
];